package org.hsieh.tr.explore.ui;

import java.net.URL;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.graphics.Image;
import org.hsieh.tr.explore.Activator;
import org.hsieh.tr.explore.exception.ExceptionHandler;

/**
 * 
 * @author xiaowei.ye xiaowei.ye@soyatec.com
 * 
 */
public class ResourceHandler {

    private static final ResourceHandler instance = new ResourceHandler();

    private ResourceHandler() {
    }

    public final static ResourceHandler getInstance() {
	return instance;
    }

    public Image getImage(String loc) {
	Image image = JFaceResources.getImage(loc);
	if (image != null)
	    return image;
	else {
	    try {
		URL imageUrl = FileLocator.find(Activator.getDefault()
			.getBundle(), new Path(loc), null);
		ImageDescriptor descriptor = ImageDescriptor
			.createFromURL(imageUrl);
		if (descriptor != null) {
		    Image newImage = descriptor.createImage();
		    JFaceResources.getImageRegistry().put(loc, newImage);
		    return newImage;
		}
	    } catch (Exception e) {
		ExceptionHandler.handle(e);
	    }
	}
	return null;
    }

    public ImageDescriptor getImageDescriptor(String loc) {
	Image image = getImage(loc);
	if (image != null) {
	    return ImageDescriptor.createFromImage(image);
	}
	return null;
    }
}
